#include "notepad.h"
#include <QVBoxLayout>
#include <QMessageBox>
#include <QApplication>
#include <QMenuBar>
#include <QString>
#include <QFileDialog>
#include <QTextStream>
#include <QPrintDialog>
#include <QPrinter>

Notepad::Notepad()
{
    openAction = new QAction(tr("&Open"),this);
    saveAction = new QAction(tr("&Save"),this);
    printAction = new QAction(tr("&Print"),this);
    quitAction = new QAction(tr("&Quit"),this);

    connect(openAction,SIGNAL(triggered()),this,SLOT(open()));
    connect(saveAction,SIGNAL(triggered()),this,SLOT(save()));
    connect(printAction,SIGNAL(triggered()),this,SLOT(print()));
    connect(quitAction,SIGNAL(triggered()),qApp,SLOT(quit()));

    fileMenu = menuBar()->addMenu(tr("&File"));
    fileMenu->addAction(openAction);
    fileMenu->addAction(saveAction);
    fileMenu->addSeparator();
    fileMenu->addAction(printAction);
    fileMenu->addAction(quitAction);

    textEdit = new QTextEdit;

    setCentralWidget(textEdit);

    setWindowTitle(tr("Notepad"));
}

void Notepad::open()
{
    QString fileName = QFileDialog::getOpenFileName(this,tr("Open File"),"",
                                                    tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::ReadOnly)) {
            QMessageBox::critical(this,tr("Error"),tr("Could not open file"));
            return;
        }
        QTextStream in(&file);
        textEdit->setText(in.readAll());
        file.close();
    }

}

void Notepad::save()
{
    QString fileName = QFileDialog::getSaveFileName(this,tr("Save File"), "",
                                                    tr("Text Files (*.txt);;C++ Files (*.cpp *.h)"));
    if (fileName != "") {
        QFile file(fileName);
        if (!file.open(QIODevice::WriteOnly)) {
            QMessageBox::critical(this,tr("Error"),tr("Could not save file"));
            return;
        }
        QTextStream out(&file);
        out << textEdit->toPlainText();
        out.flush();
        file.close();
    }
}

void Notepad::print()
{
    QPrinter printer;
    QPrintDialog printDialog(&printer,this);
    printDialog.setWindowTitle(tr("Print Document"));
    printDialog.exec();
}

void Notepad::quit()
{
    QMessageBox messageBox;
    messageBox.setWindowTitle(tr("Notepad"));
    messageBox.setText(tr("Do you really want to quit?"));
    messageBox.setStandardButtons(QMessageBox::Yes | QMessageBox::No);
    messageBox.setDefaultButton(QMessageBox::No);
    if (messageBox.exec() == QMessageBox::Yes) {
        qApp->quit();
    }
}
